# coding=utf-8
import hashlib
import traceback

from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash

from .club import Club
from .message import Message
from .. import db, login_manager
from .base import BaseModel


class Admin(UserMixin, BaseModel):
    __tablename__ = 'admin'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True)
    username = db.Column(db.String(64), unique=True, index=True)
    phone = db.Column(db.String(64), unique=True, index=True)
    gender = db.Column(db.SmallInteger,  default=1)
    password_hash = db.Column(db.String(128))
    avatar_hash = db.Column(db.String(100))
    ip = db.Column(db.String(15), default='', doc='ip')
    ip_loc = db.Column(db.String(80), default='', doc='IP地址')

    def __repr__(self):
        return '<User{}>'.format(self.username)

    def __init__(self, **kwargs):
        super(Admin, self).__init__(**kwargs)

    @staticmethod
    def insert_admin(email, username, password):
        admin = Admin(email=email, username=username, password=password)
        admin.avatar_hash = admin.hash_avatar(email)
        db.session.add(admin)
        db.session.commit()

    @staticmethod
    def hash_avatar(email):
        url = 'https://cravatar.cn/avatar/'
        email_hash = hashlib.md5(email.encode('utf-8')).hexdigest()
        return f'{url}{email_hash}.png'

    @staticmethod
    def hash_password(password):
        return generate_password_hash(password)

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    @property
    def avatar(self):
        raise AttributeError('avatar is not a readable attribute')

    @avatar.setter
    def avatar(self, email):
        self.avatar_hash = self.cravatar(email)


